<template>
	<div>
		<header ref="box1" class="flex-between-center margin-bottom-4">
			<div>
				<el-button size="small" class="item-gap" type="default" icon="el-icon-user">
					<span>人数: </span>
					<span style="font-size: 13px;font-weight: 700;">{{ ruleFrom.scheduleEmpList.length }}</span>
					<span>人</span>
				</el-button>
				<auto-bind-emp-machine-btn
					:check-data="checkData"
					@on-confirm="getDependentData"
				></auto-bind-emp-machine-btn>
			</div>
			<div>
				<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" class="search-bar-item-size2 item-gap" @on-enter="onSearchBtn"></jk-search-input>
				<jk-search-input v-model="searchParams.empName" placeholder="人员名称" class="search-bar-item-size3" show-search @on-enter="onSearchBtn"></jk-search-input>
			</div>
		</header>
		<jk-table :loading="contentLoading" border="border" :stripe="false" :data="ruleFrom.scheduleEmpList" :height="dialogTableHeight - 50">
			<vxe-column title="人员" align="center" field="empName" :width="120">
				<template slot="header">
					<div class="flex-center" style="flex-direction: column;">
						<el-button :disabled="readonly" :icon="readonly ? '' : 'el-icon-plus'" type="text" size="mini" @click="checkboxEmpDialogState = true">{{ readonly ? '人员' : '添加人员' }}</el-button>
					</div>
				</template>
				<template slot-scope="scope">
					<div class="flex-start-center width-100-percent" style="align-items: flex-end;">
						<el-button :disabled="readonly" closable type="default" size="mini" class="width-100-percent flex-start-center">
							<span style="font-size: 13px;font-weight: 700;">{{ scope.row.empName }}</span>
							<span style="font-size: 12px;white-space: nowrap;">{{ `(${scope.row.totalMachineNum}台)` }}</span>
						</el-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="岗位" align="left" field="shiftName" :min-width="100">
				<template slot="header">
					<legend-bar></legend-bar>
				</template>
				<template slot-scope="scope">
					<work-time-list
						:form-data="ruleFrom"
						:search-params="searchParams"
						:scope="scope"
						:post-list="postList"
						:check-data="checkData"
						@on-refresh="onRefresh"
					></work-time-list>
				</template>
			</vxe-column>
			<vxe-column :visible="!readonly" title="操作" align="center" field="operation" :width="80">
				<template slot-scope="scope">
					<div class="flex-center width-100-percent">
						<div class="item-gap"><jk-button :disabled="readonly" size="mini" @click="onRemoveEmpBtn(scope.row)">删除</jk-button></div>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<checkbox-emp-dialog
			:default-select-rows="ruleFrom.scheduleEmpList"
			check-key-name="empId"
			:dialog-state="checkboxEmpDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxEmpDialog"
			@on-confirm="onConfirmBtnOfCheckboxEmpDialog"
		></checkbox-emp-dialog>
		<jk-dialog
			v-model="deleteEmpDialogState"
			width="330px"
			append-to-body
			:confirm-btn-loading="deleteEmpDialogConfirmBtnLoading"
			@on-visible-change="onVisibleChangeOfDeleteEmpDialog"
			@on-confirm="onConfirmBtnOfDeleteEmpDialog"
			@on-cancel="onVisibleChangeOfDeleteEmpDialog(false)"
		>
			<el-form ref="deleteEmpForm" :model="deleteEmpForm" :rules="deleteEmpFormRules" label-position="top" label-width="120px" :show-message="false">
				<el-form-item class="margin-bottom-10" label="移除原因" prop="causeId">
					<jk-select v-model="deleteEmpForm.causeId" class="width-100-percent" size="small" :option-list="causeList"></jk-select>
				</el-form-item>
			</el-form>
		</jk-dialog>
	</div>
</template>

<script>
    import {
        workforceManagementScheduleEmpCreate,
        workforcemanagementScheduleGroupDeleteEmp, workforcemanagementScheduleGroupList,
        workforcemanagementScheduleGroupUpdate
    } from '../../../../../../api/schedule/scheduling';
    import setSpinGroupDialog from '../../set-spin-group-dialog';
    import checkboxEmpDialog from '../../checkbox-emp-dialog';
    import { systemBusinessDictPage } from '../../../../../../api/basicData/businessDict';
    import { systemPostPage } from '../../../../../../api/system/post';
    import { mathJsAdd } from '../../../../../../utils/jk/jk-cals';
    import calHeight from '../../../../../../mixins/cal-dialog-height';
    import legendBar from '../../legend-bar';
    import legendList from '../../legend-bar/lengend-list';
    import { tipsBar } from '../../../../../../utils/jk/jk-tool';
    import postPopover from './post-popover';
    import workTimeList from './work-time-list';
    import autoBindEmpMachineBtn from '../../auto-bind-emp-machine.vue';
    export default {
        mixins: [calHeight, legendList],
        components: {
            autoBindEmpMachineBtn,
            workTimeList,
            postPopover,
            legendBar,
            setSpinGroupDialog,
            checkboxEmpDialog
        },
        props: {
            readonly: { // 只读
                type: Boolean,
                default: false
            },
            checkData: {
                type: Object,
                default() {
                    return {
                        scheduleId: null,
                        scheduleGroupId: null,
                        scheduleGroupName: '',
                        shiftItem: {}
                    };
                }
            }
        },
        data() {
            return {
                ruleFrom: {
                    shiftTypeId: null,
                    groupId: null,
                    workshopName: '',
                    date: '',
                    typeId: 1,
                    scheduleEmpList: []
                },
                searchParams: {
                    workshopId: null,
                    scheduleShiftId: null,
                    scheduleId: this.checkData.scheduleId,
                    scheduleGroupId: this.checkData.scheduleGroupId,
                    empName: '',
                    machineNameOrCode: ''
                },
                deleteId: null,
                deleteEmpForm: {
                    causeId: null,
                    causeName: ''
                },
                deleteEmpFormRules: {
                    causeId: [{ required: true, trigger: 'change' }]
                },
                causeList: [],
                deleteEmpDialogConfirmBtnLoading: false,
                deleteEmpDialogState: false,
                empIdx: null,
                postList: [],
                contentLoading: false,
                checkboxEmpDialogState: false
            };
        },
        methods: {
            onRefresh() {
                this.getDependentData();
            },
            transformDateTime(e) {
                let str = e && e.split(' ') ? e.split(' ')[1] : '';
                const arr = str.split(':');
                str = arr[0] + ':' + arr[1];
                return str;
            },
            onConfirmBtnOfDeleteEmpDialog() {
                this.$refs['deleteEmpForm'].validate(valid => {
                    if (valid) {
                        this.contentLoading = true;
                        this.deleteEmpRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChangeOfDeleteEmpDialog(e) {
                if (!e) {
                    this.deleteId = null;
                    this.$set(this.deleteEmpForm, 'causeId', null);
                    this.$refs.deleteEmpForm.clearValidate([]);
                }
                this.deleteEmpDialogState = e;
            },
            deleteEmpRequest() {
                this.deleteEmpDialogConfirmBtnLoading = true;
                const params = {
                    ids: [this.deleteId],
                    scheduleEmpExceptionalCaseId: this.deleteEmpForm.causeId,
                    scheduleEmpExceptionalCaseName: this.causeList.find(x => x.id === this.deleteEmpForm.causeId).name
                };
                workforcemanagementScheduleGroupDeleteEmp({}, params).then(res => {
                    this.deleteEmpDialogConfirmBtnLoading = false;
                    this.deleteEmpDialogState = false;
                    if (res.data.status === 200) {
                        this.getDependentData();
                    }
                });
            },
            onConfirmBtnOfCheckboxEmpDialog(arr) {
                const empData = {
                    scheduleGroupId: this.checkData.scheduleGroupId,
                    empIds: arr.map(x => x.id)
                };
                this.contentLoading = true;
                workforceManagementScheduleEmpCreate(empData).then(res => {
                    if (res.data.status === 200) {
                        this.checkboxEmpDialogState = false;
                        this.getDependentData();
                    }
                });
            },

            onVisibleChangeOfCheckboxEmpDialog(e) {
                this.checkboxEmpDialogState = e;
            },
            onRemoveEmpBtn(row) {
                this.deleteId = row.id;
                this.deleteEmpDialogState = true;
            },
            updateRequest(empList = []) {
                const payload = {};
                payload.scheduleEmpList = empList;
                payload.scheduleId = this.checkData.scheduleId;
                payload.scheduleGroupId = this.checkData.scheduleGroupId;
                return workforcemanagementScheduleGroupUpdate(payload);
            },
            onConfirmBtn(item, empIdx) {
                if (item) {
                    this.ruleFrom.scheduleEmpList[empIdx].scheduleEmpPostList.push({
                        postId: item.id,
                        postName: item.name,
                        scheduleEmpMachineList: []
                    });
                } else {
                    tipsBar(this, 'validator');
                }
            },
            getCauseListRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'REMOVE_EMP_CAUSE',
                    pageSize: 100,
                    pageNo: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.causeList = res.data.res;
                    }
                });
            },
            getPostListRequest() {
                return systemPostPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.postList = res.data.res || [];
                    }
                });
            },
            getListRequest() {
                return workforcemanagementScheduleGroupList(this.searchParams).then(res => {
                    if (res.data.status === 200) {
                        if (res.data.res) {
                            const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : { scheduleEmpList: [] };
                            resData.scheduleEmpList ? resData.scheduleEmpList.map(x => {
                                x.totalMachineNum = 0;
                                x.scheduleEmpPostDateList = x.scheduleEmpPostDateList || [];
                                x.scheduleEmpPostDateList.forEach(d => {
                                    d.scheduleEmpPostList = d.scheduleEmpPostList || [];
                                    d.scheduleEmpPostList.forEach(k => {
                                        k.scheduleEmpMachineList = k.scheduleEmpMachineList || [];
                                    });
                                });
                                return x;
                            }) : [];
                            this.ruleFrom = resData;
                            this.calEmpMachineNum();
                        }
                    }
                });
            },
            calEmpMachineNum() {
                this.ruleFrom.scheduleEmpList.forEach(x => {
                    x.totalMachineNum = 0;
                    x.scheduleEmpPostDateList.forEach(d => {
                        d.scheduleEmpPostList = d.scheduleEmpPostList || [];
                        d.scheduleEmpPostList.forEach(k => {
                            x.totalMachineNum = mathJsAdd(k.scheduleEmpMachineList.length || 0, x.totalMachineNum);
                        });
                    });
                });
            },
            async getDependentData() {
                this.contentLoading = true;
                await this.getCauseListRequest();
                await this.getPostListRequest();
                await this.getListRequest();
                this.contentLoading = false;
            },
            onSearchBtn() {
                this.getDependentData();
            }
        },
        mounted() {
            this.searchParams.workshopId = this.checkData.workshopId;
            this.searchParams.scheduleId = this.checkData.scheduleId;
            this.searchParams.scheduleShiftId = this.checkData.shiftItem.id;
            this.searchParams.scheduleGroupId = this.checkData.scheduleGroupId;
            this.getDependentData();
        },
        destroyed() {
            this.$set(this.searchParams, 'machineNameOrCode', '');
            this.$set(this.searchParams, 'empName', '');
        }
    };
</script>
<style scoped lang="scss">
.remove-emp-item-icon {
    font-size: 13px;
}
.remove-emp-item-icon:hover {
    color: #2d8cf0;
}
.post-item {
    width: 100%;
    height: 100%;
    border-bottom: none;
    display: flex;
    align-items: center;
    .post-item-label {
        width: 120px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }
    .post-item-machine-container {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
    }
}
.post-item:last-child {
}
</style>
